import { cn, getFileName } from '@/lib/utils';
import { Button } from './ui/button';
import { useSettingsStore } from '@/store';
import appConfig from '@/app.config';
import { toast } from 'sonner';
import { Mutate, StoreApi, UseBoundStore } from 'zustand';
import { PostMessageType, SendTemuSettingsMessage } from '@/config';

type Props = {
  children?: React.ReactNode;
  className?: string;
  store?: UseBoundStore<Mutate<StoreApi<any>, any>>;
  suggestedName?: string;
  origin: string;
};

export default function SettingsPersistedCorssOrigin({
  children,
  className,
  store,
  suggestedName,
  origin,
  ...props
}: Props) {
  const useStore = store || useSettingsStore;
  async function exportSettings() {
    const settings = useStore.getState();
    const settingsString = JSON.stringify(settings);
    window.parent.postMessage(
      {
        type: PostMessageType.saveTemuSettings,
        data: {
          settings: settingsString,
          suggestedName: suggestedName || appConfig.settingsFilename,
        },
      },
      origin,
    );
  }

  async function importSettings() {
    window.parent.postMessage(
      {
        type: PostMessageType.importTemuSettings,
      },
      origin,
    );

    window.addEventListener(
      'message',
      async (message: MessageEvent<SendTemuSettingsMessage>) => {
        if (message.data.type === PostMessageType.sendTemuSettings) {
          const settingsString = message.data.data.settings;
          try {
            useStore.setState(JSON.parse(settingsString));
            toast.success(`成功导入配置`);
          } catch (error) {
            toast.error(`导入配置失败 ${(error as Error).message}`);
          }
        }
      },
      {
        once: true,
      },
    );
  }

  return (
    <div className={cn(className, 'felx items-center')} {...props}>
      <Button onClick={exportSettings} size="sm" className="mr-3">
        导出设置
      </Button>
      <Button onClick={importSettings} size="sm" className="">
        导入设置
      </Button>
    </div>
  );
}
